# coding=utf-8
import json
import sys
from compontent.Argument import Argument
from compontent.Browser import Browser
from compontent.Config import Config
from compontent.GetTime import getTime
from compontent.LogUtil import LogUtil
from compontent.Store import Store
from compontent.cmd.CmdManager import CmdManager

# 机器人
class Robot:
    # 名字
    name = ""
    # 浏览器
    browser = Browser()
    # 店
    store = None
    # 配置
    config = None
    # 命令行参数
    argument = None

    # 初始化机器人
    def __init__(self,name):
        self.name = name
        self.config = Config()
        self.argument = Argument()
        # 设置日志级别
        LogUtil.set_level(self.argument.get_args().log_level)
        LogUtil.info("[MiaoWa]参数集：" + str(self.argument.get_args()))
        # 创建浏览器
        self.browser = Browser.new_browser(self.argument)
        # 创建店
        self.store = Store(self.argument.get_args().store_kind)
        pass
    
    # 开始工作
    @getTime(stage="主工作")
    def start_working(self):
        if len(sys.argv) > 0:
            # 根据子命令分流执行 找到子命令
            cmdName = self.find_sub_cmd()
            cmdExecutor = CmdManager.get_instance(cmdName)
            if cmdExecutor:
                LogUtil.debug("执行命令:" + cmdName)
                cmdExecutor.execute(self)
        pass
    
    # 找到子命令
    def find_sub_cmd(self):
        index = 1
        while True:
            cmd = sys.argv[index]
            if not cmd.startswith("-"):
                return cmd
            index = index + 1

    # 关机
    def shut_down(self):
        self.browser.switch_window(0)
        self.browser.close()
        pass

    # 登录
    @getTime("登录到店")
    def do_login(self):
        # 没有加载cookie则加载
        if not self.store.is_login():
            cookies_path = self.store.get_cookies_path()
            # 找到最小需要的cookies，加快登录cookie的操作
            needs = ["aep_common_f", "xman_t"]
            # 设置cookies跳过登录
            with open(cookies_path) as f:
                list_cookies = json.loads(f.read())
            for cookie in list_cookies:
                if cookie["name"] in needs:
                    del cookie['sameSite']
                    self.browser.add_cookie(cookie)
            # 设置登录状态为True
            self.store.set_login(True)
            LogUtil.info("[store=" + self.store.get_name() + "]加载登录信息成功")
        pass

    # 登录到后端首页
    @getTime("登录到订单首页")
    def login_to_home(self):
        # 尝试到首页
        self.browser.get(self.store.home_url)
        # 登录
        self.do_login()
        pass
